package com.example.movieratingbackend.repository;

import com.example.movieratingbackend.model.Movie;
import com.example.movieratingbackend.model.MovieData;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


@Repository
@Slf4j
public class MovieRepository {


    private List<Movie> movies = new ArrayList<>();

    private final ObjectMapper objectMapper;

    public MovieRepository(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    public List<Movie> findAll() {
        return movies;
    }

    public Optional<Movie> findById(Long id) {
        return movies.stream().filter(n -> Objects.equals(n.getId(), id)).findFirst();
    }

    public Mono<Movie> saveRating(Long id, int rating) {
        Optional<Movie> movieOptional = findById(id);
        if (movieOptional.isPresent()) {
            movieOptional.get().addRating(rating);
            return Mono.just(movieOptional.get());
        } else {
            log.warn("the movie you rating is not found ");
            return Mono.empty();
        }

    }

    @PostConstruct
    public void init() {
        fetchMovies();
    }

    public void fetchMovies() {

        try {
            InputStream inputStream = getClass().getResourceAsStream("/movie.json");
            MovieData movieData = objectMapper.readValue(inputStream, MovieData.class);
            movies = movieData.getMovies();
        } catch (IOException e) {
            log.error("read json file fail");
        }
    }

}